package com.xlh.openai.handler;

import cn.hutool.core.text.StrFormatter;
import com.xlh.openai.entity.WechatUserEntity;
import com.xlh.openai.service.WechatUserService;
import me.chanjar.weixin.common.session.WxSessionManager;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.message.WxMpXmlMessage;
import me.chanjar.weixin.mp.bean.message.WxMpXmlOutMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Map;

import static me.chanjar.weixin.common.api.WxConsts.EventType;

/**
 * @author <a href="https://github.com/binarywang">Binary Wang</a>
 */
@Component
public class MenuHandler extends AbstractHandler {


    @Autowired
    private WechatUserService wechatUserService;
    /**
     * 问题问答Key
     */
    public static String ASC_QUESTION = "ASC_QUESTION";
    /**
     * 问答查询
     */
    public static String QUESTION_SEARCH = "ASC_SEARCH";
    /**
     * 调用支付
     */
    public static String TO_PAY = "ASC_PAY";



    @Override
    public WxMpXmlOutMessage handle(WxMpXmlMessage wxMessage,
                                    Map<String, Object> context, WxMpService weixinService,
                                    WxSessionManager sessionManager) {
        String msg = String.format("type:%s, event:%s, key:%s",
            wxMessage.getMsgType(), wxMessage.getEvent(),
            wxMessage.getEventKey());

        if(EventType.CLICK.equals(wxMessage.getEvent())){

            if(ASC_QUESTION.equals(wxMessage.getEventKey())){
                msg = "您好，我是您的智能小助理，请点击左下角的小键盘跟我交流吧！";
                return WxMpXmlOutMessage.TEXT().content(msg)
                        .fromUser(wxMessage.getToUser()).toUser(wxMessage.getFromUser())
                        .build();
            }
            if(QUESTION_SEARCH.equals(wxMessage.getEventKey())){
                WechatUserEntity wechatUserEntity = wechatUserService.getByOpenId(wxMessage.getFromUser());
                msg = StrFormatter.format("您好，您当前问答次数剩余{}次！", wechatUserEntity.getQuestionTime());
                return WxMpXmlOutMessage.TEXT().content(msg)
                        .fromUser(wxMessage.getToUser()).toUser(wxMessage.getFromUser())
                        .build();
            }
        }

        if (EventType.VIEW.equals(wxMessage.getEvent())) {
            return null;
        }

        return WxMpXmlOutMessage.TEXT().content(msg)
            .fromUser(wxMessage.getToUser()).toUser(wxMessage.getFromUser())
            .build();
    }

}
